package com.example.automanagement.controller;


import com.example.automanagement.entity.AutoArchives;
import com.example.automanagement.entity.AutoStatus;
import com.example.automanagement.service.ArchiveService;
import com.example.automanagement.service.AutoStatusService;
import com.example.automanagement.util.RegexUtils;
import com.example.automanagement.util.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@CrossOrigin
@RestController
public class ArchiveController {
    @Resource
    private ArchiveService archiveService;
    @Resource
    private AutoStatusService autoStatusService;


    //ToDo 分页查询 条件查询 修改 新建 删除 获取所有车牌号

    @GetMapping("/fetchPlateNums")
    public Result fetchAllPlateNums(){
        List<AutoArchives> plates = archiveService.fetchPlates();

        return Result.success(plates);
    }

    @GetMapping("/autoPageQuery")
    public Result getAutoPage() {

        List<AutoArchives> archives = archiveService.list();
        return Result.success(archives);
    }
    @PutMapping("/autoArchiveUpdate")
    public Result autoArchiveUpdate(@RequestBody AutoArchives archive){
        if(archive == null)
            return Result.error("500","请检查输入");
        archiveService.update(archive);
        return Result.success(archive);
    }
    @PostMapping("/autoArchiveInsert")
    public Result autoArchiveInsert(@RequestBody AutoArchives archive){
        if(archive == null)
            return Result.error("500","请检查输入");

        archiveService.add(archive);
        //新增插入的同时也插入status表

        String autoId = archive.getAutoId();
        if(autoId == null)
            return Result.error("500","请检查输入");

        AutoStatus autoStatus = new AutoStatus(autoId, "空闲",null);
        autoStatusService.addAutoStatus(autoStatus);

        return Result.success();
    }
    @DeleteMapping("/autoArchDelete")
    public Result autoArchiveDelete(@RequestParam("autoId") String autoId){
        AutoArchives myArchive = archiveService.getArchiveById(autoId);
        if(myArchive == null)
            return Result.error("500", "不存在对应档案 ");

        //删除车辆之前先删除对应状态
        autoStatusService.deleteAutoStatus(autoId);

        //再删除车辆档案
        archiveService.delete(myArchive);
        return Result.success(myArchive);
    }
    //获取所有车辆位置及状态
    @GetMapping("/getAutoStatusInfo")
    public Result getAutoStatusInfo(){
        List<AutoStatus> allAutoStatus = autoStatusService.getAllAutoStatus();
        return Result.success(allAutoStatus);
    }

    //根据车牌号更新车辆状态，将其更改为“空闲”
    @PutMapping("/updateAutoStatusFree")
    public Result updateAutoStatusFree(@RequestParam("autoPlateNum") String autoPlateNum){
        AutoArchives autoArchive = archiveService.getAutoIdByPlate(autoPlateNum);
        if(autoArchive == null)
            return Result.error("500", "不存在对应车辆 ");
        autoStatusService.updateAutoFree(autoArchive.getAutoId());
        return Result.success();
    }

}
